from pymodbus.client.tcp import ModbusTcpClient
import logging

# 配置日志记录，包括时间戳和详细级别
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
log = logging.getLogger(__name__)


def read_coils(client, start, count):
    try:
        result = client.read_coils(start, count)
        if result.isError():
            log.error("读取线圈寄存器时出错：%s", result)
            return None
        else:
            log.info("读取到的线圈寄存器状态（布尔值）：%s", result.bits)
            return result.bits
    except Exception as e:
        log.exception("读取线圈寄存器时发生异常：%s", e)
        return None


def read_discrete_inputs(client, start, count):
    try:
        result = client.read_discrete_inputs(start, count)
        if result.isError():
            log.error("读取离散输入寄存器时出错：%s", result)
            return None
        else:
            log.info("读取到的离散输入寄存器状态（布尔值）：%s", result.bits)
            return result.bits
    except Exception as e:
        log.exception("读取离散输入寄存器时发生异常：%s", e)
        return None


def read_holding_registers(client, start, count):
    try:
        result = client.read_holding_registers(start, count)
        if result.isError():
            log.error("读取保持寄存器时出错：%s", result)
            return None
        else:
            log.info("读取到的保持寄存器值（16位无符号整数）：%s", result.registers)
            return result.registers
    except Exception as e:
        log.exception("读取保持寄存器时发生异常：%s", e)
        return None


def read_input_registers(client, start, count):
    try:
        result = client.read_input_registers(start, count)
        if result.isError():
            log.error("读取输入寄存器时出错：%s", result)
            return None
        else:
            log.info("读取到的输入寄存器值（16位无符号整数）：%s", result.registers)
            return result.registers
    except Exception as e:
        log.exception("读取输入寄存器时发生异常：%s", e)
        return None


def clinent_modbus(device, ip, port, start, count):
    # 从字典中获取函数对象
    device = device_map.get(device)
    try:
        with ModbusTcpClient(ip, port=port) as client:
            if not client.connect():
                log.error("无法连接到Modbus服务器")
                return

            # 检查函数对象是否存在
            if device is not None:
                # 调用函数并返回结果
                return device(client, start, count)

    except Exception as e:
        log.exception("函数中发生异常：%s", e)

    # 调用主函数，传递必要的参数

device_map = {
    "01": read_coils,
    "02": read_discrete_inputs,
    "03": read_holding_registers,
    "04": read_input_registers
}
def clinent_modbus(device, ip, port, start, count):
    # 从字典中获取函数对象
    device = device_map.get(device)
    print(device, start, count)
    try:
        with ModbusTcpClient(ip, port=port) as client:
            if not client.connect():
                log.error("无法连接到Modbus服务器")
                return

            # 检查函数对象是否存在
            if device is not None:
                # 调用函数并返回结果
                info = device(client, start, count)
                print (info)
                return device(client, start, count)

    except Exception as e:
        log.exception("函数中发生异常：%s", e)

    # 调用主函数，传递必要的参数

device_map = {
    '01': read_coils,
    '02': read_discrete_inputs,
    '03': read_holding_registers,
    '04': read_input_registers
}